package com.rise.gpsapp;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceReference;

import com.rise.externalservice.IGPS;
import com.rise.externalservice.IMap;
import com.rise.externalservice.IServerMap;

public class Activator implements BundleActivator {

	private static BundleContext context;

	static BundleContext getContext() {
		return context;
	}

	private GPSServiceListener GPSServiceListener;
	private MapServiceListener mapServiceListener;
	private ServerMapServiceListener serverMapServiceListener; 
	
	private ConsumerThread consumerThread;
	
	public void start(BundleContext bundleContext) throws Exception {
		
		this.consumerThread = new ConsumerThread(null, null);
		this.GPSServiceListener = new GPSServiceListener(bundleContext, this.consumerThread);
		this.mapServiceListener = new MapServiceListener(bundleContext, this.consumerThread);
		this.serverMapServiceListener = new ServerMapServiceListener(bundleContext, this.consumerThread);
		
		String filter = "(objectclass=" + IGPS.class.getName() + ")";
		bundleContext.addServiceListener(this.GPSServiceListener, filter);
		ServiceReference[] refsGPS = 
			bundleContext.getServiceReferences(null, filter);

		filter = "(objectclass=" + IMap.class.getName() + ")";
		bundleContext.addServiceListener(this.mapServiceListener, filter);
		ServiceReference[] refsIMap = 
			bundleContext.getServiceReferences(null, filter);

		filter = "(objectclass=" + IServerMap.class.getName() + ")";
		bundleContext.addServiceListener(this.mapServiceListener, filter);
		ServiceReference[] refsIServerMap = 
			bundleContext.getServiceReferences(null, filter);				
		
		for (int i = 0; refsGPS != null && i < refsGPS.length; i++) {
			this.GPSServiceListener.serviceChanged(new ServiceEvent(
					ServiceEvent.REGISTERED, refsGPS[i]));
		}
		for (int i = 0; refsIServerMap != null && i < refsIServerMap.length; i++) {
			this.serverMapServiceListener.serviceChanged(new ServiceEvent(
					ServiceEvent.REGISTERED, refsIServerMap[i]));
		}
		for (int i = 0; refsIMap != null && i < refsIMap.length; i++) {
			this.mapServiceListener.serviceChanged(new ServiceEvent(
					ServiceEvent.REGISTERED, refsIMap[i]));
		}

	}

	public void stop(BundleContext bundleContext) throws Exception {
		this.GPSServiceListener.stopUsingService();
	}

}
